<script setup lang="ts">
import { computed } from 'vue'

defineOptions({
  name: 'BaseDialog'
})

// 定义 props
const props = defineProps<{
  modelValue: boolean // 控制对话框显示/隐藏 (v-model)
  title?: string
  width?: string // 控制对话框宽度，例如 'max-w-md', 'max-w-xl'
  showClose?: boolean // 是否显示右上角关闭按钮
}>()

// 定义 emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'close'): void // 可选的关闭事件
}>()

// 计算宽度类
const widthClass = computed(() => props.width || 'max-w-md')

// 关闭对话框
const closeDialog = () => {
  emit('update:modelValue', false)
  emit('close') // 触发关闭事件
}
</script>

<template>
  <teleport to="body">
    <transition
      enter-active-class="transition ease-out duration-200 transform"
      enter-from-class="opacity-0"
      enter-to-class="opacity-100"
      leave-active-class="transition ease-in duration-200 transform"
      leave-from-class="opacity-100"
      leave-to-class="opacity-0"
    >
      <div
        v-if="modelValue"
        class="fixed inset-0 z-40 bg-black bg-opacity-50 backdrop-blur-sm"
        @click.self="closeDialog"
      ></div>
    </transition>

    <transition
      enter-active-class="transition ease-out duration-300 transform"
      enter-from-class="opacity-0 translate-y-10 scale-95"
      enter-to-class="opacity-100 translate-y-0 scale-100"
      leave-active-class="transition ease-in duration-200 transform"
      leave-from-class="opacity-100 translate-y-0 scale-100"
      leave-to-class="opacity-0 translate-y-10 scale-95"
    >
      <div
        v-if="modelValue"
        class="fixed inset-0 z-50 flex items-center justify-center p-4"
        @click.self="closeDialog"
      >
        <!-- 对话框容器 -->
        <div
          class="relative bg-white w-full rounded-lg shadow-xl overflow-hidden flex flex-col"
          :class="[widthClass]"
        >
          <!-- 头部 -->
          <div
            v-if="title || showClose"
            class="p-4 flex items-center justify-between flex-shrink-0"
          >
            <h3 v-if="title" class="text-lg font-semibold text-gray-800">{{ title }}</h3>
            <button
              v-if="showClose !== false"
              @click="closeDialog"
              class="text-gray-400 hover:text-gray-600 focus:outline-none p-1 rounded-full hover:bg-gray-100 ml-auto"
            >
              <i class="iconfont icon-ios-close !text-xl"></i>
            </button>
          </div>

          <!-- 内容插槽 -->
          <div class="px-4 overflow-y-auto flex-grow">
            <slot>对话框内容</slot>
          </div>

          <!-- 底部插槽 -->
          <div v-if="$slots.footer" class="p-4 flex-shrink-0">
            <slot name="footer"></slot>
          </div>
        </div>
      </div>
    </transition>
  </teleport>
</template>
